<template>
  <div class="page-h5">
    <!---------------------------1.选择  -------------------->
    <div class="choice-container" v-if="selectionState">
      <div class="choice-title">
        <h3>选择登录方式</h3>
        <p>请选择您希望的登录方式</p>
      </div>

      <div class="choice-options">
        <div
          class="choice-item"
          :class="{ active: formData.status === 0 }"
          @click="handleBindExistingUser"
        >
          <div class="choice-icon">
            <Icon icon="ep:user" />
          </div>
          <div class="choice-content">
            <div class="choice-main-text">绑定已有用户</div>
            <div class="choice-sub-text">使用现有账户进行绑定</div>
          </div>
          <div class="choice-indicator">
            <div class="radio-dot" :class="{ checked: formData.status === 0 }"></div>
          </div>
        </div>

        <div
          class="choice-item"
          :class="{ active: formData.status === 1 }"
          @click="handleCreateNewUser"
        >
          <div class="choice-icon">
            <Icon icon="ep:plus" />
          </div>
          <div class="choice-content">
            <div class="choice-main-text">创建新用户</div>
            <div class="choice-sub-text">注册一个全新的账户</div>
          </div>
          <div class="choice-indicator">
            <div class="radio-dot" :class="{ checked: formData.status === 1 }"></div>
          </div>
        </div>
      </div>
    </div>
    <!------------------------ 2.绑定已有用户 ---------------------------------->
    <el-form
      ref="formLogin"
      :model="loginForm"
      :rules="LoginRules"
      class="bind-form"
      label-width="80px"
      v-if="formData.status === 0"
    >
      <!-- 标题区域 -->
      <div class="form-header">
        <LoginFormTitle class="form-title" />
        <div class="form-subtitle">
          <p>绑定已有账户</p>
          <span>使用现有账户信息进行绑定登录</span>
        </div>
      </div>

      <!-- 表单区域 -->
      <div class="form-body">
        <el-form-item label="企业名称" prop="tenantName" class="form-item">
          <el-input
            v-model.trim="loginForm.tenantName"
            :placeholder="t('login.tenantNamePlaceholder')"
            :prefix-icon="iconHouse"
            class="form-input"
            size="large"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="username" class="form-item">
          <el-input
            v-model.trim="loginForm.username"
            :placeholder="t('login.usernamePlaceholder')"
            :prefix-icon="iconAvatar"
            class="form-input"
            size="large"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" class="form-item">
          <el-input
            v-model.trim="loginForm.password"
            :placeholder="t('login.passwordPlaceholder')"
            :prefix-icon="iconLock"
            show-password
            :type="passType"
            autocomplete="new-password"
            class="form-input"
            size="large"
          />
        </el-form-item>
      </div>

      <!-- 按钮区域 -->
      <div class="form-footer">
        <XButton :title="t('login.bindUser')" class="bind-button" @click="bindNowUser" />
      </div>
      <!-- 返回 -->
      <div class="form-footer">
        <XButton title="返回" class="bind-button" @click="back" />
      </div>
    </el-form>
  </div>
  <Verify
    ref="verify"
    :captchaType="captchaType"
    :imgSize="{ width: '300px', height: '150px' }"
    mode="pop"
    @success="handleLogin"
  />
</template>

<script setup>
import { LoginStateEnum, useFormValid, useLoginState } from '@/views/Login/components/useLogin.ts'
import { weComLoginInner, weComQuickLogin } from '@/api/wecom/user/index'
import { useIcon } from '@/hooks/web/useIcon'
import * as authUtil from '@/utils/auth'
import * as LoginApi from '@/api/login'
import { cloneDeep } from 'lodash-es'
import { getAccessToken, getTenantId, getRefreshToken } from '@/utils/auth'

const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
const { t } = useI18n()
const selectionState = ref(false)
const formData = reactive({
  status: null
})
const loginForm = reactive({
  uuid: '',
  tenantName: '',
  mobileNumber: '',
  captchaVerification: ''
})
const { push } = useRouter()

const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })

const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required]
}
// 获取url的code
const getCodeFromUrl = (url) => {
  const regex = /[?&]code=([^&]*)/
  const match = url.match(regex)
  return match ? match[1] : null
}
// 随机数
const getRandomInteger = () => {
  return Math.floor(Math.random() * (10000 - 1 + 1)) + 1
}
const preData = ref({})
// 获取码
const getCode = async () => {
  const weComCode = getCodeFromUrl(window.location.href)
  console.log(weComCode, '+++++++++++')
  if (weComCode) {
    sessionStorage.setItem('weComCode', weComCode)
    const res = await weComLoginInner(weComCode)
    preData.value = res
    // 1.绑定已有 创建新的
    if (res.weUserId) {
      selectionState.value = true
      // ----------------
    } else {
      selectionState.value = false
      authUtil.setTenantId(res.tenantId)
      authUtil.setTenantSign(res.tenantSign)
      authUtil.setToken(res)
      push({ path: '/wxDetail' })
    }
  } else {
    // 获取code
    const rUrl = encodeURIComponent(window.location.href)
    const State = getRandomInteger()
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww35fee5ffaec0fa66&redirect_uri=${rUrl}&response_type=code&scope=snsapi_base&state=${State}#wechat_redirect`
    window.location.href = url
  }
}

// 绑定已有用户点击事件
const handleBindExistingUser = () => {
  formData.status = 0
  selectionState.value = false
}

// 创建新用户点击事件
const handleCreateNewUser = async () => {
  formData.status = 1
  selectionState.value = false
  const obj = cloneDeep(preData.value)
  const res = await weComQuickLogin(obj)
  if (res) {
    authUtil.setTenantId(res.tenantId)
    authUtil.setTenantSign(res.tenantSign)
    authUtil.setToken(res)
    push({ path: '/wxDetail' })
  }
}
const verify = ref()
// 绑定用户
const bindNowUser = async () => {
  const data = await validForm()
  if (!data) {
    return
  }
  verify.value.show()
}
const back = () => {
  selectionState.value = true
  formData.status = null
}
const getUserTenantId = async () => {
  const res = await LoginApi.getTenantIdByName(loginForm.tenantName)
  authUtil.setTenantId(res ? res.id : null)
  authUtil.setTenantSign(res ? res.sign : null)
}
const handleLogin = async (params) => {
  await getUserTenantId()
  loginForm.captchaVerification = params.captchaVerification
  const res2 = await LoginApi.login(loginForm)
  if (res2) {
    try {
      const obj = cloneDeep(preData.value)
      obj.sysUserId = res2.userId
      // 在快捷登录
      const data = await weComQuickLogin(obj)
      if (res2) {
        authUtil.setTenantId(res2.tenantId)
        authUtil.setTenantSign(res2.tenantSign)
        authUtil.setToken(res2)
        push({ path: '/wxDetail' })
      }
    } catch {}
  }
}
onMounted(() => {
  if (getRefreshToken()) {
    push({ path: '/wxDetail' })
  } else {
    getCode()
  }
})
</script>

<style scoped lang="scss">
.page-h5 {
  width: 100vw;
  min-width: 300px;
  height: 100vh;
}
.choice-container {
  flex: 1;
  padding: 0 24px;
}
.choice-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.choice-item {
  display: flex;
  align-items: center;
  padding: 20px 16px;
  border: 2px solid #e8e8e8;
  border-radius: 12px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;

  &:hover {
    border-color: #407fff;
    background: rgba(64, 127, 255, 0.02);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 127, 255, 0.15);
  }

  &.active {
    border-color: #407fff;
    background: rgba(64, 127, 255, 0.05);

    .choice-icon {
      background: linear-gradient(135deg, #407fff 0%, #5a8cff 100%);
      color: white;
    }

    .choice-main-text {
      color: #407fff;
      font-weight: 600;
    }
  }

  &:active {
    transform: translateY(0);
  }
}

.choice-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  transition: all 0.3s ease;
  flex-shrink: 0;

  :deep(.iconify) {
    font-size: 20px;
    color: #666;
    transition: all 0.3s ease;
  }
}

.choice-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.choice-main-text {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
  transition: all 0.3s ease;
}

.choice-sub-text {
  font-size: 13px;
  color: #888;
  line-height: 1.4;
}

.choice-indicator {
  margin-left: 12px;
  flex-shrink: 0;
}

.radio-dot {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 50%;
  position: relative;
  transition: all 0.3s ease;

  &.checked {
    border-color: #407fff;

    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      width: 8px;
      height: 8px;
      background: #407fff;
      border-radius: 50%;
      transform: translate(-50%, -50%);
    }
  }
}

.bind-form {
  padding: 0;
}

// 表单头部
.form-header {
  background: #2091f6;

  padding: 40px 30px 30px;
  text-align: center;
  color: white;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 4px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 2px;
  }
}

.form-title {
  :deep(.login-title) {
    color: white !important;
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 8px;
  }
}

.form-subtitle {
  p {
    font-size: 20px;
    font-weight: 500;
    margin: 0 0 8px 0;
    color: rgba(255, 255, 255, 0.95);
  }

  span {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.8);
    line-height: 1.4;
  }
}

// 表单主体
.form-body {
  padding: 40px 30px 20px;
}

.form-item {
  margin-bottom: 24px;

  :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 500;
    color: #374151;
    margin-bottom: 8px;
    line-height: 1.5;
  }

  :deep(.el-form-item__content) {
    line-height: normal;
  }
}

.form-input {
  :deep(.el-input__wrapper) {
    border-radius: 12px;
    border: 2px solid #e5e7eb;
    box-shadow: none;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    background: #f9fafb;

    &:hover {
      border-color: #d1d5db;
      background: #ffffff;
    }

    &.is-focus {
      border-color: #667eea;
      background: #ffffff;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
  }

  :deep(.el-input__inner) {
    font-size: 15px;
    color: #374151;
    padding: 12px 16px;
    height: auto;

    &::placeholder {
      color: #9ca3af;
      font-size: 14px;
    }
  }

  :deep(.el-input__prefix) {
    left: 16px;

    .el-input__prefix-inner {
      color: #6b7280;
      font-size: 16px;
    }
  }

  :deep(.el-input__suffix) {
    right: 16px;

    .el-input__suffix-inner {
      color: #6b7280;
    }
  }
}

// 表单底部
.form-footer {
  padding: 10px 30px 10px;
}

.bgc-white {
  width: 100%;
  height: 50px;
  background: #ffffff;
  border-radius: 12px;
  color: #606266;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);

    &::before {
      left: 100%;
    }
  }

  &:active {
    transform: translateY(0);
  }

  :deep(.el-button) {
    background: transparent !important;
    border: none !important;
    color: white !important;
    font-size: 16px !important;
    font-weight: 600 !important;
    width: 100% !important;
    height: 100% !important;
  }
}
.bind-button {
  width: 100%;
  height: 50px;
  background: #2091f6;
  border: none;
  border-radius: 12px;
  color: white;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);

    &::before {
      left: 100%;
    }
  }

  &:active {
    transform: translateY(0);
  }

  :deep(.el-button) {
    background: transparent !important;
    border: none !important;
    color: white !important;
    font-size: 16px !important;
    font-weight: 600 !important;
    width: 100% !important;
    height: 100% !important;
  }
}
</style>
